package com.lmb.controller;


import com.lmb.bean.Reset;
import com.lmb.bean.UserLogin;
import com.lmb.mapper.UserLoginDao;
import com.lmb.service.UserLoginService;
import com.lmb.util.Page;
import com.lmb.util.PasswordUtil;
import com.lmb.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin //允许跨域访问
@RequestMapping("/userlogin")
public class UserLoginController {
    @Autowired
    UserLoginService userLoginService;
//    @Autowired
//    private UserLoginDao userLoginDao;

    @PostMapping
    public Result add(@RequestBody UserLogin userLogin)//@RequestBody将前台发送的json数据转为java对象
    {
        String pwd=userLogin.getUser_password();//获取密码
        userLogin.setUser_password(PasswordUtil.getEncryption(pwd));//密码加密
        Object obj=userLoginService.add(userLogin);//调用业务逻辑层方法
        return Result.success("新增数据保存成功",obj);
    }
    @DeleteMapping("{id}")
    public Result del(@PathVariable("id") Integer id){
        Object obj=userLoginService.del(id);
        return Result.success("删除成功",obj);
    }
    @PutMapping
    public Result edit(@RequestBody UserLogin userLogin){
        String pwd=userLogin.getUser_password();//获取密码
        if(pwd!=null) {
            userLogin.setUser_password(PasswordUtil.getEncryption(pwd));//密码加密
        }
        Object obj=userLoginService.edit(userLogin);
        return Result.success("编辑信息保存成功",obj);
    }
    @GetMapping("all")
    public Result all( UserLogin userLogin){
        Object obj=userLoginService.all(userLogin);
        return Result.success(obj);
    }
    @GetMapping("{id}")
    public Result one(@PathVariable("id") Integer id){
        Object obj=userLoginService.one(id);
        return Result.success(obj);
    }
    @GetMapping("page")
    public Result page(Page page,UserLogin userLogin){
        //分页查询
        //查询一个有多少条 数据
        //查询当前页的数据
        //将以上数据封装到Page对象中
        userLoginService.page(page,userLogin);
        //返回给page对象
        return Result.success(page);

    }
    @PostMapping("reset")
    public Result reset(@RequestBody Reset reset){
        String pwd= reset.getOld_password();
        String new_pwd= reset.getNew_password();
        Integer user_id=reset.getUser_id();
        try {
            UserLogin user=userLoginService.reset(pwd,new_pwd,user_id);
            return Result.success("密码修改成功",user);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail(500,e.getMessage());
        }

    }
}